/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.smartcar

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * Service for managing connection and data communication with a GATT server hosted on a
 * given Bluetooth LE device.
 */
class TransferSocketService : Service() {

    private var serverSocket: ServerSocket? = null
    private var videoReceiveIp: String? = null
    private var commandListener: CommandListener? = null
    private var executorService: ExecutorService = Executors.newSingleThreadExecutor()

    fun commandListenerInitialize() {
        try { //开启服务、指定端口号
            if(serverSocket == null){
                serverSocket = ServerSocket(8820)
                commandListener = CommandListener(this)
                commandListener?.start()
            }
        } catch (e: IOException) {
            e.printStackTrace()
            return
        }
    }

    fun setVideoReceiveIp(ip: String) {
        videoReceiveIp = ip
    }
    fun transferVideo(data: Any) {
        executorService.execute(TransferVideoRunnable(data, this))
        Log.d("log", "TransferVideo: ")
    }

    private fun broadcastUpdate(action: String, data: String) {
        val intent = Intent(action)
        intent.putExtra("data", data)
        sendBroadcast(intent)
    }

    private val binder: IBinder = LocalBinder()

    fun close() {
        serverSocket?.close()
        commandListener?.interrupt()
    }

    override fun onBind(intent: Intent): IBinder? {
        return binder
    }

    override fun onUnbind(intent: Intent): Boolean {
        close()
        return super.onUnbind(intent)
    }

    internal inner class LocalBinder : Binder(), ITransferSocketServiceBinder {
        override fun getService(): TransferSocketService {
            return this@TransferSocketService
        }
    }

    class CommandListener(var service: TransferSocketService) : Thread() {
        private val serverSocket : ServerSocket = service.serverSocket!!
        override fun run() {
            while (true) {
                try {
                    val socket = serverSocket.accept()
                    val `is` = socket.getInputStream()
                    val reader = InputStreamReader(`is`)
                    val bufReader = BufferedReader(reader)
                    var s: String? = null
                    val sb = StringBuffer()
                    while (bufReader.readLine().also { s = it } != null) {
                        sb.append(s)
                    }

                    service.broadcastUpdate(CAR_COMMAND, sb.toString())

                    `is`.close()
                    reader.close()
                    bufReader.close()
                    Log.d("命令", "Command$sb")
                    socket.close() // 关闭socket
                } catch (e: Exception) {
                    Log.d("出错", "SocketListener")
                    return
                }
                //执行操作
                if (this.isInterrupted()){
                    break;
                }
            }
        }

    }

    internal class TransferVideoRunnable(var data: Any, var service: TransferSocketService) : Runnable {
        override fun run() {
            try {
                if(service.videoReceiveIp != null){
                    val socket = Socket(service.videoReceiveIp, 8819)
                    if(socket.isConnected){
                        val os = socket.getOutputStream()
                        //写入要发送给服务器的数据
                        os.write(data as ByteArray)
                        os.flush()
                        socket.shutdownOutput()
                        os.close()
                    }
                }
            } catch (e: Exception) {
                Log.e("log", "TransferVideoRunnableError ")
                e.printStackTrace()
            }
        }
    }
    companion object {
        const val CAR_COMMAND : String = "com.smartcar.CAR_COMMAND"
    }

}



